package com.guodi.model.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guodi.core.tool.utils.StringUtil;
import com.guodi.model.utils.ExcelUtil;
import com.guodi.core.tool.api.R;
import com.guodi.model.constant.IdtIndicatorsConst;
import com.guodi.model.entity.IdtIndicators;
import com.guodi.model.entity.IdtIndicatorsDir;
import com.guodi.model.entity.IdtIndicatorsType;
import com.guodi.model.entity.IdtMonitorValue;
import com.guodi.model.mapper.IdtIndicatorsCountMapper;
import com.guodi.model.service.*;
import com.guodi.model.utils.RegularUtils;
import com.guodi.model.vo.*;
import com.guodi.system.vo.OrgVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class IdtIndicatorsCountServiceImpl implements IIdtIndicatorsCountService {

    private static String MONITOR_WARNING_CODE = "monitor-warning";
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private IIdtIndicatorsTypeService iIdtIndicatorsTypeService;
    @Resource
    private IdtIndicatorsCountMapper idtIndicatorsCountMapper;
    @Resource
    private IIdtMonitorValueService iIdtMonitorValueService;
    @Resource
    private IIdtIndicatorsService idtIndicatorsService;
    @Resource
    private IRedisDictService iRedisDictService;
    @Resource
    private IIdtIndicatorsDirService iIdtIndicatorsDirService;


    @Override
    public R getIdtIndicatorsVals(String divisionCode, String year) {
        Map<String, Object> resultMap = new HashMap<>();
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, year, divisionCode);
        List<ApiIndicatorsDirCountVo> vos = this.listDirByCode(divisionCode, year, one.getId());
        List<ApiIndicatorsDirCountVo> createtree = this.createTree(one.getId(), vos);
        Map<String, Integer> collect = new LinkedHashMap<>();
        for (ApiIndicatorsDirCountVo vo : createtree) {
            collect.put(vo.getName(), vo.getChildren().size());
        }
        resultMap.put("countData", collect);
        resultMap.put("listData", createtree);
        return R.data(resultMap);
    }

    @Override
    public void exportIdtIndicatorsVals(String divisionCode, String year, HttpServletResponse response) {
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, year, divisionCode);
        List<ApiIndicatorsDirCountVo> vos = this.listDirByCode(divisionCode, year, one.getId());
        List<ApiIndicatorsDirCountVo> createTree = this.createTree(one.getId(), vos);
        List<ApiIndicatorsDirCountVo> resultList = new ArrayList<>();
        this.analysisTree(createTree, resultList);

        List<ApiIndicatorsDirExcelVo> excelVos = new ArrayList<>();
        int i = 1;
        for (ApiIndicatorsDirCountVo vo : resultList) {
            ApiIndicatorsDirExcelVo excelVo = new ApiIndicatorsDirExcelVo();
            excelVo.setXh(i);
            excelVo.setName(StringUtils.isBlank(vo.getName()) ? "-" : vo.getName());
            excelVo.setDivisionName(StringUtils.isBlank(vo.getDivisionName()) ? "-" : vo.getDivisionName());
            excelVo.setYear(StringUtils.isBlank(vo.getYear()) ? "-" : vo.getYear() + "年");
            excelVo.setMonitorValue(StringUtils.isBlank(vo.getMonitorValue()) ? "-" : vo.getMonitorValue());
            excelVo.setIdtType(StringUtils.isBlank(vo.getIdtType()) ? "-" : vo.getIdtType());
            excelVo.setIdtBaseData(StringUtils.isBlank(vo.getIdtBaseData()) ? "-" : vo.getIdtBaseData());
            excelVo.setIdtDutyCompany(StringUtils.isBlank(vo.getIdtDutyCompany()) ? "-" : vo.getIdtDutyCompany());
            excelVo.setUpdateTime(vo.getUpdateTime() == null ? "-" : sdf.format(vo.getUpdateTime()));
            excelVos.add(excelVo);
            i++;
        }
        ExcelUtil.exportExcel(excelVos, null, "指标维度统计台账", ApiIndicatorsDirExcelVo.class, "指标维度统计台账.xls"
                , response);
    }

    @Override
    public R getDataSourceList(String divisionCode, String year) {
        Map<String, Object> resultMap = new HashMap<>();
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, year, divisionCode);
        List<ApiIndicatorsDirCountVo> vos = this.listDirByCode(divisionCode, year, one.getId());
        Map<String, Integer> collect = new LinkedHashMap<>();
        collect.put("指标填报", vos.size());
        resultMap.put("countData", collect);
        List<ApiIndicatorsDirCountVo> list = vos.stream().filter(v -> "2".equals(v.getType())).collect(Collectors.toList());
        resultMap.put("listData", list);
        return R.data(resultMap);
    }

    @Override
    public void exportDataSourceList(String divisionCode, String year, HttpServletResponse response) {
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, year, divisionCode);
        List<ApiIndicatorsDirCountVo> vos = this.listDirByCode(divisionCode, year, one.getId());
        List<ApiIndicatorsDirCountVo> list = vos.stream().filter(v -> "2".equals(v.getType())).collect(Collectors.toList());
        List<ApiDataSourceExcelVo> excelVos = new ArrayList<>();
        int i = 1;
        for (ApiIndicatorsDirCountVo vo : list) {
            ApiDataSourceExcelVo excelVo = new ApiDataSourceExcelVo();
            excelVo.setXh(i);
            excelVo.setIdtBaseData(vo.getIdtBaseData());
            excelVo.setIdtDutyCompany(vo.getIdtDutyCompany());
            excelVo.setName(vo.getName() + "（" + vo.getIdtUnit() + "）");
            excelVo.setUpdateTime(sdf.format(vo.getUpdateTime()));
            excelVos.add(excelVo);
            i++;
        }
        ExcelUtil.exportExcel(excelVos, null, "数据来源统计台账", ApiDataSourceExcelVo.class, "数据来源统计台账.xls"
                , response);
    }

    @Override
    public R getDutyCompanyList(String divisionCode, String year) {
        Map<String, Object> resultMap = new HashMap<>();
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, year, divisionCode);
        if (one == null) {
            return R.fail("指标体系为空");
        }
        List<ApiIndicatorsDirCountVo> vos = this.listDirByCode(divisionCode, year, one.getId());
        List<ApiIndicatorsDirCountVo> list = vos.stream().filter(v -> "2".equals(v.getType())).collect(Collectors.toList());
        Boolean flag = true;
        for (int i = 0; i < list.size(); i++) {
            if (StringUtil.isBlank(list.get(i).getIdtDutyCompanyType())) {
                flag = false;
                break;
            }
        }
        if (!flag) {
            return R.fail("指标项责任单位类型字段有空值");
        }
        Map<String, List<ApiIndicatorsDirCountVo>> listMap = list.stream().collect(Collectors.groupingBy(ApiIndicatorsDirCountVo::getIdtDutyCompanyType));
        //责任单位类型统计
        Map<String, Object> map = new HashMap<>();
        for (Map.Entry<String, List<ApiIndicatorsDirCountVo>> entry : listMap.entrySet()) {
            map.put(entry.getKey(), CollectionUtils.isEmpty(entry.getValue()) ? 0 : entry.getValue().size());
        }
        resultMap.put("dutyCompanyType", map);

        //局内处室、局外处室
        Map<String, String> dutyCompanyTypeMap = iRedisDictService.getItemMaps(IdtIndicatorsConst.DUTY_COMPANY_TYPE);
        for (Map.Entry<String, String> entry : dutyCompanyTypeMap.entrySet()) {
            List<ApiIndicatorsDirCountVo> sideist = listMap.get(entry.getValue());
            Map<String, Long> collect = sideist.stream().filter(x -> StringUtils.isNotBlank(x.getIdtDutyCompany())).collect(Collectors.groupingBy(ApiIndicatorsDirCountVo::getIdtDutyCompany, Collectors.counting()));
            resultMap.put(entry.getKey(), collect);
        }

        resultMap.put("listData", list);

        return R.data(resultMap);
    }

    @Override
    public void exportDutyCompanyList(String divisionCode, String year, HttpServletResponse response) {
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, year, divisionCode);
        List<ApiIndicatorsDirCountVo> vos = this.listDirByCode(divisionCode, year, one.getId());
        List<ApiIndicatorsDirCountVo> list = vos.stream().filter(v -> "2".equals(v.getType())).collect(Collectors.toList());

        List<ApiDutyCompanyExcelVo> excelVos = new ArrayList<>();
        int i = 1;
        for (ApiIndicatorsDirCountVo vo : list) {
            ApiDutyCompanyExcelVo excelVo = new ApiDutyCompanyExcelVo();
            excelVo.setXh(i);
            excelVo.setDivisionName(vo.getDivisionName());
            excelVo.setIdtBaseData(vo.getIdtBaseData());
            excelVo.setIdtDutyCompany(vo.getIdtDutyCompany());
            excelVo.setIdtDutyCompanyType(vo.getIdtDutyCompanyType());
            excelVo.setName(vo.getName());
            excelVo.setMonitorValue(vo.getMonitorValue());
            excelVo.setUpdateTime(sdf.format(vo.getUpdateTime()));
            excelVos.add(excelVo);
            i++;
        }
        ExcelUtil.exportExcel(excelVos, null, "责任单位统计台账", ApiDutyCompanyExcelVo.class, "责任单位统计台账.xls"
                , response);
    }

    @Override
    public R getIndicatorsTreeList(String divisionCode, String year, String keyword, String idtType) {
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, year, divisionCode);
        List<ApiIndicatorsDirCountVo> vos = this.listDirByCode(divisionCode, year, one.getId());
        List<ApiIndicatorsDirCountVo> list = vos.stream().filter(v -> "2".equals(v.getType())).collect(Collectors.toList());

        //指标类型map
        Map<String, String> idtTypeMap = iRedisDictService.getItemMaps(IdtIndicatorsConst.DICT_INDICATORS_TYPE);

        Map<String, List<ApiIndOverviewVo>> map = new HashMap<>();
        for (ApiIndicatorsDirCountVo indicatorsDirCountVo : list) {
            ApiIndOverviewVo entity = new ApiIndOverviewVo();
            BeanUtils.copyProperties(indicatorsDirCountVo, entity);
            entity.setName(indicatorsDirCountVo.getName() + "（" + indicatorsDirCountVo.getIdtUnit() + "）");
            entity.setValue(indicatorsDirCountVo.getMonitorValue());
            entity.setUpdateStatus(StringUtils.isNotBlank(entity.getValue()) ? "已更新" : "未更新");
            entity.setDataDimension("指标填报");

            List<ApiIndOverviewVo> factorResults = new ArrayList<>();
            if (!CollectionUtils.isEmpty(indicatorsDirCountVo.getFactors())) {
                for (ApiIndicatorsDirCountVo factor : indicatorsDirCountVo.getFactors()) {
                    ApiIndOverviewVo factorEntity = new ApiIndOverviewVo();
                    BeanUtils.copyProperties(factor, factorEntity);
                    factorEntity.setName(factor.getName());
                    factorEntity.setValue(factor.getMonitorValue());
                    factorEntity.setUpdateStatus(StringUtils.isNotBlank(entity.getValue()) ? "已更新" : "未更新");
                    factorEntity.setDataDimension("指标填报");
                    factorResults.add(factorEntity);
                }
            }
            entity.setChildren(factorResults);
            List<ApiIndOverviewVo> orDefault = map.getOrDefault(entity.getParentName(), new ArrayList<>());
            orDefault.add(entity);
            map.put(entity.getParentName(), orDefault);
        }

        LambdaQueryWrapper<IdtIndicatorsDir> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtIndicatorsDir::getParentId, one.getId());
        wrapper.orderByAsc(IdtIndicatorsDir::getSort);
        List<IdtIndicatorsDir> dirs = this.iIdtIndicatorsDirService.list(wrapper);

        List resultList = new ArrayList();
        if (!CollectionUtils.isEmpty(dirs)) {
            for (IdtIndicatorsDir dir : dirs) {
                Map<String, Object> objectMap = new HashMap<>();
                List<ApiIndOverviewVo> orDefault = map.getOrDefault(dir.getName(), new ArrayList<>());
                objectMap.put("name", dir.getName());
                int size = orDefault.stream().filter(v -> "已更新".equals(v.getUpdateStatus())).collect(Collectors.toList()).size();
                objectMap.put("count", size);
                objectMap.put("total", orDefault.size());
                List<ApiIndOverviewVo> voList = new ArrayList<>();
                for (ApiIndOverviewVo vo : orDefault) {
                    if (StringUtils.isNotBlank(keyword) && !vo.getName().contains(keyword)) {
                        continue;
                    }
                    if (StringUtils.isNotBlank(idtType) && !Objects.equals(idtTypeMap.getOrDefault(idtType, ""), vo.getIdtType())) {
                        continue;
                    }
                    voList.add(vo);
                }
                objectMap.put("list", voList);

                resultList.add(objectMap);
            }
        }
        return R.data(resultList);
    }

    @Override
    public void exportIndicatorsTreeList(String divisionCode, String year, String keyword, String idtType, String parentName, HttpServletResponse response) {
        R r = this.getIndicatorsTreeList(divisionCode, year, keyword, idtType);
        List datas = (List) r.getData();


        ClassPathResource resource = new ClassPathResource("template/数据汇聚【模板】.xlsx");
        InputStream inputStream;
        try {
            inputStream = resource.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);

            // 创建数据行
            if (!CollectionUtils.isEmpty(datas)) {
                //指定筛选某一个维度的数据
                List list = new ArrayList();
                for (Object object : datas) {
                    Map<String, Object> objectMap = (Map<String, Object>) object;
                    List<ApiIndOverviewVo> voList = (List<ApiIndOverviewVo>) objectMap.getOrDefault("list", new ArrayList<>());
                    Map<String, Object> map = new HashMap<>();
                    map.put("name", objectMap.get("name"));
                    map.put("list", voList);

                    if (StringUtils.isNotBlank(parentName) && !parentName.equals(objectMap.get("name"))) {
                        continue;
                    }
                    list.add(map);

                }
                this.writeToSheet(list, workbook);
            }
            try {
                response.reset();
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(year + "年体检评估指标.xlsx", "UTF-8"));
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "GET,POST");
                OutputStream outputStream = response.getOutputStream();
                workbook.write(outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void writeToSheet(List list, XSSFWorkbook workbook) {
        //模板第一個sheet
        XSSFSheet sheet = workbook.getSheetAt(0);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        //目前最后行数下标
        int writeRow = sheet.getPhysicalNumberOfRows();
        //序号
        int total = 0;
        //统一样式
        XSSFCellStyle commonStyle = workbook.createCellStyle();
        commonStyle.setAlignment(HorizontalAlignment.CENTER);//设置水平居中
        commonStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置垂直居中
        commonStyle.setWrapText(true);//自动换行
        for (int i = 0; i < list.size(); i++) {
            //该维度占行数
            int voSize = 0;

            Map<String, Object> map = (Map<String, Object>) list.get(i);
            List<ApiIndOverviewVo> voList = (List<ApiIndOverviewVo>) map.getOrDefault("list", new ArrayList<>());

            for (int j = 0; j < voList.size(); j++) {
                ApiIndOverviewVo vo = voList.get(j);

                int a = (CollectionUtils.isEmpty(vo.getChildren()) ? 1 : vo.getChildren().size());
                //编号
                ExcelUtil.mergeCell(sheet, 2, 2, writeRow, writeRow + a - 1, vo.getIdtCode(), commonStyle);
                //指标项
                ExcelUtil.mergeCell(sheet, 3, 3, writeRow, writeRow + a - 1, vo.getName(), commonStyle);
                //数据维度
                ExcelUtil.mergeCell(sheet, 4, 4, writeRow, writeRow + a - 1, vo.getDataDimension(), commonStyle);
                //指标类别
                ExcelUtil.mergeCell(sheet, 5, 5, writeRow, writeRow + a - 1, vo.getIdtType(), commonStyle);
                //范围
                ExcelUtil.mergeCell(sheet, 6, 6, writeRow, writeRow + a - 1, vo.getScope(), commonStyle);
                //指标值
                ExcelUtil.mergeCell(sheet, 11, 11, writeRow, writeRow + a - 1, vo.getValue(), commonStyle);

                if (!CollectionUtils.isEmpty(vo.getChildren())) {
                    int num = vo.getChildren().size();
                    for (int z = 0; z < num; z++) {
                        //基础数据源
                        ExcelUtil.mergeCell(sheet, 7, 7, writeRow, writeRow, vo.getChildren().get(z).getName(), commonStyle);
                        //责任单位
                        ExcelUtil.mergeCell(sheet, 8, 8, writeRow, writeRow, vo.getChildren().get(z).getIdtDutyCompany(), commonStyle);
                        //更新状态
                        ExcelUtil.mergeCell(sheet, 9, 9, writeRow, writeRow, vo.getChildren().get(z).getUpdateStatus(), commonStyle);
                        //基础数据值
                        ExcelUtil.mergeCell(sheet, 10, 10, writeRow, writeRow, vo.getChildren().get(z).getValue(), commonStyle);
                        //序号
                        total++;
                        voSize++;
                        ExcelUtil.mergeCell(sheet, 0, 0, writeRow, writeRow, String.valueOf(total), commonStyle);
                        writeRow++;
                    }
                } else {
                    //基础数据源
                    ExcelUtil.mergeCell(sheet, 7, 7, writeRow, writeRow, vo.getName(), commonStyle);
                    //责任单位
                    ExcelUtil.mergeCell(sheet, 8, 8, writeRow, writeRow, vo.getIdtDutyCompany(), commonStyle);
                    //更新状态
                    ExcelUtil.mergeCell(sheet, 9, 9, writeRow, writeRow, vo.getUpdateStatus(), commonStyle);
                    //基础数据值
                    ExcelUtil.mergeCell(sheet, 10, 10, writeRow, writeRow, vo.getValue(), commonStyle);
                    //序号
                    total++;
                    voSize++;
                    ExcelUtil.mergeCell(sheet, 0, 0, writeRow, writeRow, String.valueOf(total), commonStyle);
                    writeRow++;
                }
            }
            String parentName = (String) map.getOrDefault("name", "");
            //一级
            ExcelUtil.mergeCell(sheet, 1, 1, writeRow - voSize, writeRow - 1, parentName, commonStyle);
        }
    }


    /**
     * @描述: 通用获取对应指标体系以及监测值
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/6/8 9:59
     **/
    private List<ApiIndicatorsDirCountVo> listDirByCode(String divisionCode, String year, String parentId) {
        String divisionName = this.iIdtMonitorValueService.getNameByDivisionCode(divisionCode);
        //监测值
        LambdaQueryWrapper<IdtMonitorValue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtMonitorValue::getYear, Integer.valueOf(year));
        wrapper.eq(IdtMonitorValue::getDivisionCode, divisionCode);
        wrapper.last("order by (case when modify_time is null then create_time else modify_time end) desc nulls last");
        List<IdtMonitorValue> values = this.iIdtMonitorValueService.list(wrapper);
        //指标，监测值
        Map<String, List<IdtMonitorValue>> idtIdValMap = values.stream().collect(Collectors.groupingBy(IdtMonitorValue::getIndicatorsId));
        //<指标编码，指标>
        Map<String, IdtIndicators> idtIndicatorsMap = iIdtIndicatorsDirService.mapCode2IdtIndicators();

        // 获取所有子单位
        List<OrgVO> list = idtIndicatorsCountMapper.listOrg();
        Map<String, String> deptMap = new HashMap<>();
        for (OrgVO org : list) {
            deptMap.put(org.getId().toString(), org.getOrgName());
        }
        //指标类型map
        Map<String, String> idtTypeMap = iRedisDictService.getItemMaps(IdtIndicatorsConst.DICT_INDICATORS_TYPE);
        //责任单位类型map
        Map<String, String> dutyCompanyTypeMap = iRedisDictService.getItemMaps(IdtIndicatorsConst.DUTY_COMPANY_TYPE);
        //指标范围map
        Map<String, String> idtScopeMap = iRedisDictService.getItemMaps(IdtIndicatorsConst.DICT_INDICATORS_SCOPE);

        List<ApiIndicatorsDirCountVo> treeList = this.idtIndicatorsCountMapper.listDirByCode(parentId);

        //用于存放筛选处理后的数据
        List<ApiIndicatorsDirCountVo> resultList = new ArrayList<>();

        for (ApiIndicatorsDirCountVo vo : treeList) {
            //处理责任单位多级中文名问题
            String dutyCodes = vo.getIdtDutyCompany();
            if (org.apache.commons.lang.StringUtils.isNotBlank(dutyCodes)) {
                vo.setIdtDutyCompany(idtIndicatorsService.getDeptNameStr(dutyCodes, deptMap));
            }
            //指标类型
            if (StringUtils.isNotBlank(vo.getIdtType())) {
                vo.setIdtType(idtTypeMap.get(vo.getIdtType()));
            }
            //责任单位
            if (StringUtils.isNotBlank(vo.getIdtDutyCompanyType())) {
                vo.setIdtDutyCompanyType(dutyCompanyTypeMap.get(vo.getIdtDutyCompanyType()));
            }
            //指标范围
            if (StringUtils.isNotBlank(vo.getScope())) {
                vo.setScope(idtScopeMap.get(vo.getScope()));
            }

            //监测值赋值
            if (Objects.equals("2", vo.getType())) {
                vo.setDivisionCode(divisionCode);
                vo.setDivisionName(divisionName);
                List<IdtMonitorValue> monitorValueList = idtIdValMap.get(vo.getIndicatorsId());
                if (!CollectionUtils.isEmpty(monitorValueList)) {
                    IdtMonitorValue monitorValue = monitorValueList.get(0);
                    vo.setMonitorValue(monitorValue.getMonitorValue());
                    vo.setUpdateTime(monitorValue.getMonitorTime() == null ? monitorValue.getCreateTime() : monitorValue.getModifyTime());
                    vo.setYear(year);
                }

                //有指标因子
                if (StringUtils.isNotBlank(vo.getCalculateResult())) {
                    List<String> idtCodes = RegularUtils.extractString(vo.getCalculateResult());
                    List<ApiIndicatorsDirCountVo> calculateList = new ArrayList<>();
                    for (String code : idtCodes) {
                        IdtIndicators idtIndicators = idtIndicatorsMap.get(code);
                        if (idtIndicators != null) {
                            ApiIndicatorsDirCountVo entity = new ApiIndicatorsDirCountVo();
                            entity.setIndicatorsId(idtIndicators.getId());
                            entity.setIdtCode(idtIndicators.getCode());
                            entity.setName(idtIndicators.getName());
                            entity.setCalculateResult(idtIndicators.getCalculateResult());
                            entity.setIdtBaseData(idtIndicators.getBaseData());
                            entity.setIdtUnit(idtIndicators.getUnit());
                            entity.setSort(idtIndicators.getSort());

                            //指标范围
                            if (StringUtils.isNotBlank(idtIndicators.getScope())) {
                                entity.setScope(idtScopeMap.get(idtIndicators.getScope()));
                            }
                            //监测值
                            List<IdtMonitorValue> monitorValues = idtIdValMap.get(entity.getIndicatorsId());
                            if (!CollectionUtils.isEmpty(monitorValues)) {
                                IdtMonitorValue monitorValue = monitorValues.get(0);
                                entity.setMonitorValue(monitorValue.getMonitorValue());
                                entity.setUpdateTime(monitorValue.getMonitorTime() == null ? monitorValue.getCreateTime() : monitorValue.getModifyTime());
                                entity.setYear(year);
                            }
                            //处理责任单位多级中文名问题
                            String factosDutyCodes = idtIndicators.getDutyCompany();
                            if (org.apache.commons.lang.StringUtils.isNotBlank(factosDutyCodes)) {
                                entity.setIdtDutyCompany(idtIndicatorsService.getDeptNameStr(factosDutyCodes, deptMap));
                            }
                            calculateList.add(entity);
                        }
                    }
                    vo.setFactors(calculateList);
                }
            }
            resultList.add(vo);
        }

        return resultList;
    }

    /**
     * @描述: 创建树结构
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/6/8 9:59
     **/
    private List<ApiIndicatorsDirCountVo> createTree(String parentId, List<ApiIndicatorsDirCountVo> list) {
        List tree = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ApiIndicatorsDirCountVo vo = list.get(i);
            if (vo.getParentId().equals(parentId)) {
                tree.add(vo);
                List children = createTree(vo.getId(), list);
                if (children != null && !children.isEmpty()) {
                    vo.setChildren(children);
                } else {
                    vo.setChildren(new ArrayList<>());
                }
            }
        }
        return tree;
    }

    /**
     * @描述: 解析树结构
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/6/8 10:00
     **/
    private void analysisTree(List<ApiIndicatorsDirCountVo> treeList, List<ApiIndicatorsDirCountVo> resultList) {
        if (!CollectionUtils.isEmpty(treeList)) {
            for (ApiIndicatorsDirCountVo tree : treeList) {
                ApiIndicatorsDirCountVo entity = new ApiIndicatorsDirCountVo();
                BeanUtils.copyProperties(tree, entity);
                entity.setChildren(null);
                resultList.add(entity);
                analysisTree(tree.getChildren(), resultList);
            }
        }
    }
}
